package topuc.com.mvp.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

import topuc.com.mvp.R;
import topuc.com.mvp.bean.ItemObject;

/**
 * Created by apls on 2018/12/13.
 */
public class CustomWheelView extends View {

    /**
     * 显示多少个Item，默认显示7个
     */
    private int itemCount = 7;
    /**
     * 每个Item的高度
     */
    private int unitHeight = 100;
    /**
     * 控件的宽度
     */
    private int viewWidth;
    /**
     * 控件的高度
     */
    private int viewHeight;

    private Paint mPaint;

    private float downY;
    private float moveY;

    /**
     * 刷新界面
     */
    private static final int REFRESH_VIEW = 0x001;

    private List<String> dataList = new ArrayList<>();
    private List<ItemObject> itemList = new ArrayList<>();

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case REFRESH_VIEW:
                    invalidate();
                    break;
                default:
                    break;
            }
        }

    };

    public CustomWheelView(Context context) {
        super(context);
        initData();
    }

    public CustomWheelView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
        initData();
    }

    public CustomWheelView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
        initData();
    }

    private void init(Context context, AttributeSet attrs) {

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setTextSize(20);

        TypedArray wheeldata = context.obtainStyledAttributes(attrs, R.styleable.WheelView);
        itemCount = wheeldata.getInt(R.styleable.WheelView_itemNumber, itemCount);
        unitHeight = (int) wheeldata.getDimension(R.styleable.WheelView_unitHeight,unitHeight);

        wheeldata.recycle();

        viewHeight = itemCount * unitHeight;

//        unitHeight=wheeldata.getDimension(R.styleable.WheelView_unitHeight,unitHeight);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        viewWidth = getMeasuredWidth();
        Log.d("CustomWheelView", "onMeasure viewWidth:" + viewWidth);
        if (viewWidth != 0) {
            setMeasuredDimension(viewWidth, itemCount * unitHeight);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        drawLine(canvas);
        drawItem(canvas, viewWidth, itemCount * unitHeight);
    }

    /**
     * 初始化列表数据
     *
     * @param mList
     */
    public void setData(List<String> mList) {

        for (int i = 0; i < mList.size(); i++) {

            Log.d("CustomWheelView", "setData viewWidth:" + viewWidth);

            ItemObject itemObject = new ItemObject();
            itemObject.setX(i);
            itemObject.setY(i * unitHeight);
            Log.d("CustomWheelView", "i * unitHeight:" + i * unitHeight);
            itemObject.setText(mList.get(i));
            itemList.add(itemObject);
        }

        invalidate();
    }

    /**
     * 绘制每一个Item
     *
     * @param canvas
     */
    private void drawItem(Canvas canvas, int viewWidth, int viewHeight) {

        for (int i = 0; i < itemList.size(); i++) {
            itemList.get(i).drawSelf(canvas, viewWidth, viewHeight);
        }

    }

    private void drawLine(Canvas canvas) {

        canvas.drawLine(0, viewHeight / 2 + unitHeight / 2, viewWidth, viewHeight / 2 + unitHeight / 2, mPaint);
        canvas.drawLine(0, viewHeight / 2 - unitHeight / 2, viewWidth, viewHeight / 2 - unitHeight / 2, mPaint);

    }

    private void initData() {

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:

                downY = event.getY();

                break;

            case MotionEvent.ACTION_MOVE:

                moveY = event.getY() - downY;
                actionMove(moveY);

                break;

            case MotionEvent.ACTION_UP:

                actionUp(moveY);

                break;
        }
        return true;
    }

    /**
     * @param moveY 移动的距离
     */
    private void actionUp(float moveY) {

        int distance = 0;

        /**
         * up所执行的操作
         * 1.将最新的Y坐标更新
         * 2.如果停止移动时，未有条目在正中间，则自动移动到正中间，此时需计算移动到正中间所需的距离
         * 3.计算出距离，每一个Item都应该移动这个距离
         */
        if (moveY > 0) {

            for (int i = 0; i < itemList.size(); i++) {

                if (itemList.get(i).isSelected(viewHeight, viewWidth)) {
                    //如果moveY>0，则列表从上往下绘制
                    distance = itemList.get(i).moveToSelected(viewHeight, unitHeight, moveY);
                    Log.d("WheelView","actionUp distance:" + distance+",i:"+i);
                    break;
                }
            }

        } else {

            for (int i = itemList.size() - 1; i >= 0; i--) {

                if (itemList.get(i).isSelected(viewHeight, viewWidth)) {
                    //如果moveY>0，则列表从上往下绘制
                    distance = itemList.get(i).moveToSelected(viewHeight, unitHeight, moveY);
                    Log.d("WheelView", "actionUp distance:" + distance+",i:"+i);
                    break;
                }
            }
        }

        /**
         * 设置每一项新的坐标
         */
        for (ItemObject item : itemList) {

            item.newY((int) moveY);
        }

        /**
         * 将Item移动到中间位置
         */
        slowMove(distance);
        invalidate();
    }

    /**
     * 移动到中间位置
     *
     * @param distance
     */
    private void slowMove(final int distance) {

        final int speed = 1;

        /**
         * 1.获取距离
         * 2.每个item移动
         */
        new Thread(new Runnable() {
            @Override
            public void run() {

                float move = distance > 0 ? distance : distance * (-1);
                int i = distance > 0 ? 1 : (-1);

                Log.d("WheelView", "move" + move);

                int count = 0;

                while (true) {

                    move = move - speed;
                    if (move <= 0) {

                        break;
                    }

                    for (ItemObject item : itemList) {
                        item.newY(speed * i);
                    }

                    count = count + 1;
                    Log.d("WheelView", "speed*i:" + speed * i + ",speed:" + speed + ",i:" + i + ",count:" + count);

                    Message rMessage = new Message();
                    rMessage.what = REFRESH_VIEW;
                    handler.sendMessage(rMessage);

                    try {
                        Thread.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

            }
        }).start();


        for (ItemObject item : itemList) {


        }

    }

    /**
     * 移动
     *
     * @param moveY
     */
    private void actionMove(float moveY) {

        for (ItemObject item : itemList) {

            item.move((int) moveY);
        }
        invalidate();
    }
}